package com.mooc.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientTest {

    public static void main(String[] args) {

        Socket socket = null;
        PrintStream printStream = null;
        Scanner scanner = null;
        BufferedReader bufferedReader = null;

        try {
            socket = new Socket("127.0.0.1" , 8888);
            scanner = new Scanner(System.in);
            printStream = new PrintStream(socket.getOutputStream());
            bufferedReader = new BufferedReader(
                    new InputStreamReader(
                            socket.getInputStream())
            );

            while (true) {

                //1.写入客户端往服务端发送的消息
                System.out.println("请输入要发送的内容：");
                String message = scanner.next();

                //2.写入socket通信，发送到服务端
                printStream.println(message);


                //3.业务出口
                if ("bye".equalsIgnoreCase(message)) {
                    System.out.println("聊天结束!");
                    break;
                }

                //4.获取服务端返回的消息并打印到终端
                String readLine = bufferedReader.readLine();
                System.out.println("服务端返回的消息是：" + readLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bufferedReader) bufferedReader.close();
                if (null != scanner) scanner.close();
                if (null != printStream) printStream.close();
                if (null != socket) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
